package database;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.swing.JTextArea;

public class DatabaseMySQL implements DBInterface {
	
	private String userName, password, dbPath;
	private Connection connection;
	
	

	@Override
	public void initialise(String user, String pass, String path) {
		
		userName = user;
		password = pass;
		dbPath = path;
		
	}

	@Override
	public boolean connect() {
		
		try {
			connection = DriverManager.getConnection("jdbc:mysql://" + dbPath, userName, password);
			
			return true;
			
		} catch (SQLException e) {
			
			e.printStackTrace();
			return false;
		}
		
	}

	@Override
	public boolean commit() {
		try { 
			connection.commit();
			return true;
		} catch (SQLException e) {
			e.printStackTrace();
			
			return false;
		}
		
	}

	@Override
	public boolean rollback() {
		
		try {
			connection.rollback();
			return true;
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
			
		}
	}

	@Override
	public boolean close() {
		
		try { 
		connection.close();
		return true;
		
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		}
	}

	@Override
	public boolean doSQL(String query) throws SQLException {
		connect();
		
		Statement stmt;
		
		
			stmt = connection.createStatement();
			System.out.println("This is the query inside the doSQL method " + query);
			stmt.executeUpdate(query);
			stmt.close();
			close();
			return true;
		
	}

	@Override
	public String[][] returnQuery(String query) {
		
		connect();
		
		StringBuilder output = new StringBuilder();
		Statement stmt;
		
		try {
			stmt = connection.createStatement();
			ResultSet rs = stmt.executeQuery(query);
			int rowCount = 0;
			
			while (rs.next()) {
				
				for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) {
					
					output.append(rs.getString(i) + "~");
				}
				output.append("\n");
				rowCount++;
				
			}
			
			String[][] result = new String[rs.getMetaData().getColumnCount()][rowCount];
			
			String s[] = output.toString().split("~");
			
			int i = 0;
			for (int y = 0; y < result[0].length; y++){
				for (int x = 0; x < result.length; x++){
					
					result[x][y] = s[i];
					i++;
					
				}
			}
			rs.close();
			stmt.close();
			close();
			return result;
		}catch (SQLException e) {
			close();
			e.printStackTrace();
			return null;
		}
		
	}

	@Override
	public void printQuery(String[][] s) {
		
		for (int y = 0; y < s[0].length; y++) {
			for (int x = 0; x < s.length; x++) {
				
				//System.out.print(s[x][y] + "\t");
			}
			//System.out.println();
		}
		
	}

	
	

	
	
	

}
